# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from onlypy.utils.webutils import login_required, admin_required, is_admin, object_list
from onlypy.blog.forms import CommentForm
from onlypy.blog.models import Comment
from django.http import HttpResponse
from django.template.context import RequestContext

from google.appengine.ext.db import GqlQuery
from google.appengine.api import mail

import logging
from models import Post, Category
from google.appengine.api import users
from google.appengine.ext import db

from forms import PostForm

import settings

@admin_required
def add_post(request):
    if request.method == 'GET':
        form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST)
        logging.getLogger().debug(form)
        if form.is_valid():
            post = form.save(commit=False) #form.save(commit=False)返回一个form实例，commit为True则会将form存入datastore
            post.author = users.get_current_user()
            post.put()
            post.category.post_count += 1
            post.category.put()
            return HttpResponseRedirect('/')

    return render_to_response('blog/operate_post.html', {'form': form}, context_instance=RequestContext(request))



@admin_required
def list_all_post(request):
    posts = Post.all()
    posts.order('-create_time');

    return object_list(request, queryset=posts, allow_empty=True,
            template_name='blog/list_post.html', extra_context={'is_admin': is_admin()},
            paginate_by=settings.POST_LIST_PAGE_SIZE)

def list_post(request):
    posts = Post.all().order('-create_time')
    if (not is_admin()):
        posts = posts.filter("is_published", True)

    return object_list(request, queryset=posts, allow_empty=True,
                template_name='blog/list_post.html', extra_context={'is_admin': is_admin()},
                paginate_by=settings.POST_LIST_PAGE_SIZE)

@admin_required
def add_category(request):
    if request.method == 'POST':
        category = Category()
        category.name = request.POST['name']
        category.put();

        return HttpResponseRedirect('/category/add')

    return render_to_response('blog/add_category.html', context_instance=RequestContext(request))

@admin_required
def delete_post(request, post_id):
    post = Post.get_by_id(int(post_id))
    if not post:
        raise Http404
    post.category.post_count -= 1;
    post.category.put()
    db.delete(post)
    return HttpResponseRedirect('/post/list_all/')

@admin_required
def edit_post(request, post_id):
    post = Post.get_by_id(int(post_id))
    if not post:
        raise Http404

    if request.method == 'GET':
        form = PostForm({'title': post.title,
                         'content': post.content,
                         'tag': post.tag,
                         'category': post.category.key(),
                         'is_published': post.is_published})
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            modified_post = form.save(commit=False)
            if modified_post.category.key() != post.category.key():
                post.category.post_count -= 1
                post.category.put()
                modified_post.category.post_count += 1
                modified_post.category.put()
            post.title = modified_post.title
            post.category = modified_post.category
            post.tag = modified_post.tag
            post.content = modified_post.content
            post.is_published = modified_post.is_published
            post.put()
            return HttpResponseRedirect('/post/%s/'%post.key().id())

    return render_to_response('blog/operate_post.html', {'form': form}, context_instance=RequestContext(request))

def view_post(request, post_id):
    post = Post.get_by_id(int(post_id))
    if not post:
        raise Http404

    if not is_admin() and not post.is_published:
        raise Http404

    if request.method == 'POST':
        comment = Comment()
        comment.content = request.POST['comment']
        comment.author = users.get_current_user()
        comment.post = post
        comment.put()

        post.comment_count = post.comment_count + 1
        post.put()

        mail.send_mail(sender="yangyinfei.app@gmail.com",
                       to=post.author.email(),
                       subject=(u'OnlyPython - 你的文章%s有了新评论'%post.title).encode('utf8'),
                       body=(u'''%s在你的文章%s上留了评论:

%s

点击这个链接回复: http://yangyin7.appspot.com/post/%s/''' %(comment.author.nickname(), post.title, comment.content, post.key().id())).encode('utf8')
                       )

        return HttpResponseRedirect('/post/%s' % post.key().id())

    post.read_count = post.read_count + 1
    post.put()

    comments = Comment.all().filter('post', post).order('create_time')
    return render_to_response('blog/view_post.html',
                              {'post':post,
                               'comments': comments,
                               'is_admin': is_admin(),
                               }, context_instance=RequestContext(request))

def contains_user(users, user):
    for u in users:
        if u.email() == user.email():
            return True
    return False

def update(request):
    pass
#    posts = Post.all()
#    for post in posts:
#        if not post.category.post_count:
#            post.category.post_count = 1
#        else:
#            post.category.post_count = post.category.post_count + 1
#        post.category.put()
#
#    return HttpResponse('OK')

def about(request):
    return render_to_response('about.html', context_instance=RequestContext(request))

def list_category_post(request, category_id):
    category = Category.get_by_id(int(category_id))
    if not category:
        raise Http404

    posts = Post.all().filter('category', category).filter('is_published', True).order('-create_time')
    return object_list(request, queryset=posts, allow_empty=True,
            template_name='blog/list_category_post.html', extra_context={'is_admin': is_admin(), 'category': category},
            paginate_by=settings.POST_LIST_PAGE_SIZE)

def search(request):
    if request.GET.has_key('keywords'):
        keywords = request.GET['keywords']
        logging.getLogger().info(keywords)
        posts = Post.all().search(keywords).order('-create_time')

        return object_list(request, queryset=posts, allow_empty=True,
                template_name='blog/search_post.html', extra_context={'keywords': keywords},
                paginate_by=settings.POST_LIST_PAGE_SIZE)
    else:
        return HttpResponseRedirect('/')

def sitemap(request):
    str = '''<?xml version="1.0" encoding="UTF-8"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
               <url>
                  <loc>http://www.onlypython.com/</loc>
                  <changefreq>weekly</changefreq>
                  <priority>0.9</priority>
               </url>
        '''

    posts = Post.all().filter('is_published', True)
    for post in posts:
        str += '''<url>
                      <loc>http://www.onlypython.com/post/%s/</loc>
                      <changefreq>monthly</changefreq>
                      <priority>0.8</priority>
                   </url>
                '''%post.key().id()

    categories = Category.all()
    for category in categories:
        str += '''<url>
                      <loc>http://www.onlypython.com/category/%s/</loc>
                      <changefreq>daily</changefreq>
                      <priority>0.8</priority>
                   </url>
                '''%category.key().id()
    str += '</urlset>'
    return HttpResponse(str, content_type='text/xml')

def post_links(request):
    posts = Post.all().order('-create_time')
    if (not is_admin()):
        posts = posts.filter("is_published", True)

    return render_to_response('blog/post_links.html', {'posts': posts})